<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/2/7
 * Time: 上午8:18
 * 小程序设置
 */

namespace app\agenttest\controller;

use app\common\model\Agent;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\System;
use app\common\model\WxOpen;

use app\common\model\XcxInfo;
use app\common\model\XcxSet;
use app\common\model\Yuyue;
use think\Controller;
use think\Session;
use Wechat\Wxobjopen;

class Microprogram extends AgenttestBase
{
    //小程序管理
    public function index(){
        return $this->fetch();
    }

    //设置小程序密钥
    public function setappsecret()
    {
        if (request()->isAjax()) {
            $option = $this->options2();
            $data['xcx_appsecret'] = request()->post('xcx_appsecret');
            $map['authorizer_appid'] = $option['authorizer_appid'];
            $Wxopen = new WxOpen();
            $add = $Wxopen->save($data, $map);
            if ($add) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = 1;
                $data['message'] = "操作失败";
            }
            return json($data);
        }
    }


    //设置服务器域名
    public function set_xcx_domain()
    {
        $options = $this->options2();
        $wxObj = new Wxobjopen($options);
        //END
        $info['requestdomain'] = "https://os.wunengkeji.com";
        $info['wsrequestdomain'] = "wss://os.wunengkeji.com";
        $info['uploaddomain'] = "https://os.wunengkeji.com";
        $info['downloaddomain'] = "https://os.wunengkeji.com";
        //END
        $param['action'] = "add";
        $param['requestdomain'] = $info['requestdomain'];
        $param['wsrequestdomain'] = $info['wsrequestdomain'];
        $param['uploaddomain'] = $info['uploaddomain'];
        $param['downloaddomain'] = $info['downloaddomain'];
        if (request()->isAjax()) {
            $errcode = $wxObj->set_xcx_domain($param);
            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
                $data['$param'] = $param;
                $data['$options'] = $options;

            }
            return json($data);
        } else {
            $Wxopen = new WxOpen();
            $open = $Wxopen->where(['authorizer_appid' => $options['authorizer_appid']])->value('xcx_appsecret');
            $this->assign('open', $open);
            $this->assign('info', $info);
            return $this->fetch();
        }

    }


    //获取体验二维码
    public function getqrcode()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $s = $wxObj->xcx_getqrcode();
            return $s;
        }
    }

    //获取小程序可选目录
    public function get_category()
    {
        $options = $this->options2();
        $wxObj = new Wxobjopen($options);
        $ss = $wxObj->xcx_getcategory();
        if (isset($ss['category_list'][0])) {
            $data['first_class'] = $ss['category_list'][0]['first_class'];
            $data['second_class'] = $ss['category_list'][0]['second_class'];
            $data['first_id'] = $ss['category_list'][0]['first_id'];
            $data['second_id'] = $ss['category_list'][0]['second_id'];
        } else {
            $data['first_class'] = "";
            $data['second_class'] = "";
            $data['first_id'] = "";
            $data['second_id'] = "";
        }
        return $data;

    }

    //获取小程序的第三方提交代码的页面配置
    public function get_page()
    {
        $options = $this->options2();
        $wxObj = new Wxobjopen($options);
        $ss = $wxObj->xcx_getpage();
        return $ss['page_list'][0];
    }


    //绑定体验者
    public function bind_tester()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $param['wechatid'] = request()->post('wechatid');
            $errcode = $wxObj->xcx_bind_tester($param);//绑定体验者
            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);
        } else {
            return $this->fetch();
        }
    }

    //解绑体验者
    public function unbindtester()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $param['wechatid'] = request()->post('wechatid');
            $errcode = $wxObj->xcx_unbind_tester($param);//解绑体验者
            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);
        }
    }

    //小程序提交代码  设置基本信息
    public function sub_program()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $sarr = Session::get('user');
            $Agent = new Agent();
            $uid = $sarr['uid'];
            $agents = $Agent->where(array('uid'=>$uid))->find();
            //END
            $templateId = request()->post('template_id');
            $version = request()->post('user_version');
            $descript = request()->post('user_desc');
            $appId = request()->post('extAppid');
            $title = request()->post('title');
            $copyright = request()->post('copyright');
            $logo_data = request()->post('logo');
//            $logo_data = $img;
            $extJson = array(
                'extAppid' => $appId,
                'extEnable' => true,
                'ext' => array(
                    "attr" => array(
                        'logo' => trim($logo_data),                 //logo
                        'weburl' => "https://os.wunengkeji.com/apis.php",                 //服务器地址
                        'siteurl' => "",                //请求地址
                        'title' => $title,                //请求地址
                        'sign_appid' => $agents['sign_appid'],        //用于实现签名的appid
                        'sign_key' => $agents['sign_key'],            //用户实现签名的appkey
                        'copyright' => $copyright,            //用户实现签名的appkey
                    )
                )
            );
            $params = array(
                'template_id' => $templateId,
                'user_version' => $version,
                'user_desc' => $descript,
                'ext_json' => json_encode($extJson, JSON_UNESCAPED_UNICODE)
            );

            $errcode = $wxObj->xcx_commit($params);//提交代码
            $data['$params'] = $params;
            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            if (trim($logo_data) !== $agents['xcx_cardus_logo']) {
                $Agent->where(['id' => $agents['id']])->update(['xcx_cardus_logo' => trim($logo_data)]);
            }
            return json($data);

        } else {
            $sarr = Session::get('user');
            $Agent = new Agent();
            $WxOpen = new WxOpen();
            $uid = $sarr['uid'];
            $agents = $Agent->where(array('uid'=>$uid))->find();
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $xcxget = $wxObj->get_xcx_search();
            if ($xcxget['errcode'] == 0) {
                $xcxstatu = $xcxget['status'];
            } else {
                $xcxstatu = "";
            }
            $users = $WxOpen->where(['id' => $agents['wx_open_id_xcx_cardus']])->find();
            $XcxSet = new XcxSet();
            $xcxset = $XcxSet->where(['type'=>2])->order('id desc')->find();
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $siteurl = $http_type . $_SERVER['HTTP_HOST'];
            $this->assign('siteurl', $siteurl);
            $map['agent_id'] = $agents['id'];
            $xcxinfo = XcxInfo::where($map)->order('id desc')->select();;
            $this->assign('xcxinfo', $xcxinfo);
            $this->assign('xcxstatu', $xcxstatu);
            $this->assign('xcxset', $xcxset);
            $this->assign('wx_open', $users);
            $this->assign('agents', $agents);
            return $this->fetch();
        }


    }

    //提交审核
    public function sub_program_sh()
    {
        if (request()->isAjax()) {
            $datac = $this->get_category();
            if ($datac['first_class'] !== "" || $datac['second_class'] !== "") {
                $arr_param = request()->post();
                $options = $this->options2();
                $wxObj = new Wxobjopen($options);
                $param['address'] = $this->get_page();
                $param['tag'] = request()->post('tag');
                if ($datac['first_class'] !== "") {
                    $param['first_class'] = $datac['first_class'];
                    $param['first_id'] = $datac['first_id'];
                }
                if ($datac['second_class'] !== "") {
                    $param['second_class'] = $datac['second_class'];
                    $param['second_id'] = $datac['second_id'];
                }
                $param['title'] = "首页";
                //参数拼接END
                //最后传给微信的参数
                $params['item_list'][] = $param;
                if ($arr_param['version_desc']) {
                    $params['version_desc'] = $arr_param['version_desc'];
                }
                $res_data['$params'] = $params;
                $errcode = $wxObj->xcx_submitaudit($params);//提交审核
                if ($errcode['errcode'] == 0) {
                    $sarr = Session::get('user');
                    $Agent = new Agent();
                    $WxOpen = new WxOpen();
                    $uid = $sarr['uid'];
                    $agents = $Agent->where(array('uid'=>$uid))->find();
                    //END
                    $sdata['agent_id'] = $agents['id'];
                    $sdata['auditid'] = $errcode['auditid'];
                    $sdata['addtime'] = time();
                    $sdata['status'] = 2;
                    $XcxInfo = new XcxInfo();
                    $XcxInfo->save($sdata);
                    //END
                    $res_data['code'] = 0;
                    $res_data['message'] = "操作成功";
                } else {
                    $res_data['code'] = $errcode['errcode'];
                    $res_data['message'] = $errcode['errmsg'];
                }
            } else {
                $res_data['code'] = 9999;
                $res_data['message'] = "没有设置所属行业，请先至公众平台完善小程序信息";
            }
            return json($res_data);

        }


    }

    //小程序撤销审核
    public function xcx_uncode()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $ss = $wxObj->get_xcx_uncode();
            if ($ss['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $ss['errcode'];
                $data['message'] = $ss['errmsg'];
            }
            return json($data);
        }
    }


    //检查审核状态
    public function xcx_getauditstatus()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
//        $params["auditid"] = 420527434;
            $params["auditid"] = request()->post('auditid');
            $errcode = $wxObj->xcx_getauditstatus($params);
            $XcxInfo = new XcxInfo();
            if ($errcode['errcode'] == 0) {
                if ($errcode['status'] == 2) {
                    $data['code'] = 2;
                    $data['message'] = "当前小程序正在审核中";

                } elseif ($errcode['status'] == 1) {
                    $XcxInfo->save(['status' => 1, 'shtime' => time(), 'reason' => $errcode['reason']], ['auditid' => $params["auditid"]]);
                    $data['code'] = 1;
                    $data['message'] = "审核失败  " . $errcode['reason'];
                } elseif ($errcode['status'] == 0) {
                    $XcxInfo->save(['status' => 0, 'shtime' => time(), 'reason' => ''], ['auditid' => $params["auditid"]]);
                    $data['code'] = 0;
                    $data['message'] = "当前小程序审核成功";
                }
            }
            return json($data);

        }

    }

    //设置小程序可查看状态
    public function set_xcx_search()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            // "status":0, //1表示不可搜索，0表示可搜索
            $param['status'] = request()->post('status');
            $errcode = $wxObj->set_xcx_search($param);

            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);

        }

    }

    //发布小程序
    public function xcx_release()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            // "status":0, //1表示不可搜索，0表示可搜索
            $param = [];;
            $errcode = $wxObj->xcx_release($param);

            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);

        }
    }

    public function options2()
    {
        $WxOpen = new WxOpen();
        $Agent=new Agent();
        //END
        $sarr = Session::get('user');
        $uid = $sarr['uid'];
        $config = $Agent->where(array('id'=>15))->find();                               //将我方开放平台作为小程序的开放平台
        //END
        $agents = $Agent->where(array('uid'=>$uid))->find();
        $users = $WxOpen->where(['id' => $agents['wx_open_id_xcx_cardus']])->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            //END
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }
}